package com.example.chat.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.chat.model.Message
import com.example.chat.repository.MessageRepository
import com.example.featuresdk.model.User
import com.example.chat.repository.TopicRepository
import com.example.featuresdk.vo.Status
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.*
import javax.inject.Inject
import kotlin.random.Random

/**
 * View model is the business logic layer responsible for
 * 1. Use repository (data access layer) to manage changes to data model (business data layer)
 * 2. Publish changes to uiState observed by View (Compose) which will reflect the changes
 * 3. Handle events from View and perform corresponding business logic (commands), e.g. calculation, validation
 */
@HiltViewModel
class TopicListViewModel
@Inject constructor(private val topicRepository: TopicRepository,
                    private val messageRepository: MessageRepository): ViewModel() {

    companion object{
        const val TAG = "TopicListViewModel"
    }
    val uiState = TopicListState()

    init {
        Log.i(TAG,"init: $this")

        launch {
            uiState.topics = topicRepository.get(User.ME.id!!)
//            uiState.participants = topicRepository.getAllParticipants()
//
//            topicRepository.get(User.ME.id!!).collect {
//
//                uiState.topics = flowOf(it)
//            }

            simulateMessage()
        }
    }

    private fun launch(action: suspend ()->Unit){
        viewModelScope.launch {
            try {
                action()
            }catch (e: CancellationException){
                //ignore
            }
            catch (t: Throwable){
                uiState.status.value = Status.Error
                uiState.message.value = t.message?:""
                Log.e(TAG,"Error",t)
            }
        }
    }

    override fun onCleared() {
        Log.i(TAG,"onCleared(): $this")
        super.onCleared()
    }

    private suspend fun simulateMessage(){

            var count = 0

            val contents = listOf("Hello, nice to see you!",
                "Great, have a good day","I like magic ^_^",
                "What a lovely day","I love China","Jetpack is great")

            while (true){
                delay(1000)
                val id = Random.nextLong(10) + 1

                val message = Message(null,id,id, contents[Random.nextInt(contents.size)], null)
                messageRepository.create(message)

                topicRepository.updateSummary(message.topicId, message.text?:"", message.timestamp)

                topicRepository.updateNewCount(message.topicId)
                if(count++ > 5){
                    break
                }
            }

    }
}